package semantic.search.logos.foundation.dataprovider.ontology;

import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.sdb.SDBFactory;
import com.hp.hpl.jena.sdb.Store;

public class SparqlConnection {

	public static final String LOGOS_DOMAIN = "http://www.ufba.br/logos#";
	private static SparqlConnection instance;
	
	public static SparqlConnection instance()
	{
		if (instance == null)
			instance = new SparqlConnection();
		
		return instance;
	}
	
	// ------------------------------------------

	private Dataset dataset;
	private Store store;
	
	public SparqlConnection()
	{		
		connect();
	}
	
	private void connect()
	{
		System.out.println(getPath("conf/sdb-mysql-innodb.ttl"));
		store = SDBFactory.connectStore(getPath("conf/sdb-mysql-innodb.ttl")) ;
						
		// connect store to dataset
	    dataset = SDBFactory.connectDataset(store);
	}
	
	public ResultSet query(String sparqlQuery)
	{
		sparqlQuery =  	"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " +
						"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
						"PREFIX logos: <"+LOGOS_DOMAIN+"> " +
						sparqlQuery;
		
		System.out.println(sparqlQuery);
		
		QueryExecution qe = QueryExecutionFactory.create(sparqlQuery, dataset);
		try
		{
			ResultSet rs = qe.execSelect();
			return rs;
		} 
		finally 
		{
			// Fazer isso indisponibiliza os dados do resultset.
			//qe.close();
		}
	}
	
	// -----------------------------------------------
	
	public String getPath(String path)
	{
		String binPath = this.getClass().getClassLoader().getResource("").getPath();
		return "file:///" + binPath.replace("bin/", "")  + path;
	}

}
